package com.javastar.modules.storage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javastar.common.exception.AssertUtil;
import com.javastar.common.exception.ErrorCode;
import com.javastar.common.redis.RedisKey;
import com.javastar.common.redis.RedisUtil;
import com.javastar.modules.storage.entity.StorageConfigEntity;
import com.javastar.modules.storage.mapper.StorageConfigMapper;
import com.javastar.modules.storage.service.StorageConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

/**
 * <p>
 * 第三方文件存储配置表 服务实现类
 * </p>
 *
 * @author Java星球
 * @since 2023-07-25
 */
@Service
public class StorageConfigServiceImpl extends ServiceImpl<StorageConfigMapper, StorageConfigEntity> implements StorageConfigService {
    @Autowired
    private RedisUtil redisUtil;

    @Value("${storage.team-name}")
    private String teamName;
    @Value("${storage.pojo-name}")
    private String pojoName;

    /**
     * 单文件上传
     * @param file
     * @param type
     * @return
     */
    @Override
    public String uploadSingleFile(MultipartFile file, Integer type) {
        /* 保存路径: javastar/pojo-name/image|video/2023-07/25/xxx */
        // 从redis获取配置信息
        StorageConfigEntity storageConfig = redisUtil.getBean(RedisKey.STORAGE_CONFIG, "", StorageConfigEntity.class);
        if (storageConfig == null) {
            // 从db获取数据
            storageConfig = lambdaQuery().eq(StorageConfigEntity::getEnable, 1).last("limit 1").one();
            redisUtil.set(RedisKey.STORAGE_CONFIG, "", storageConfig);
        }

        String url = "";
        // aliyun
        if (storageConfig.getAliyunEnable() == 1) {
            url = aliyunUploadSingleFile(storageConfig, file, type);
        }

        return url;
    }

    /**
     * 阿里云单文件上传
     * @param file
     * @param type
     * @return
     */
    private String aliyunUploadSingleFile(StorageConfigEntity storageConfig, MultipartFile file, Integer type) {
        OSS ossClient = null;
        String url = "";
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder().build(storageConfig.getAliyunEndpoint(), storageConfig.getAliyunAccessKeyId(), storageConfig.getAliyunAcessKeySecret());

            // 构造文件路径和名称
            InputStream inputStream = file.getInputStream();
            String fileDirectory = pojoName + (type == 1 ? "/image/" : "/video/") + DateUtil.format(new Date(), "yyyy-MM/dd/");
            String newFileName = fileDirectory + IdUtil.simpleUUID();

            // 上传
            ossClient.putObject(storageConfig.getAliyunBucketName(), newFileName, inputStream);

            // 拼接访问地址
            url = "https://" + storageConfig.getAliyunBucketName() + "." + storageConfig.getAliyunEndpoint() + "/" + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
            AssertUtil.error(ErrorCode.INTERNAL_SERVER_ERROR);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        return url;
    }
}
